package com.foodorder.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 测试控制器
 */
@RestController
@RequestMapping("/test")
public class TestController {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> data = new HashMap<>();
        data.put("status", "OK");
        data.put("timestamp", LocalDateTime.now().toString());
        data.put("message", "应用程序运行正常");
        return data;
    }
    
    @GetMapping("/ping")
    public String ping() {
        return "pong";
    }
    
    @GetMapping("/reset-admin")
    public Map<String, Object> resetAdmin() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 固定使用123456作为密码
            String password = "123456";
            String encodedPassword = passwordEncoder.encode(password);
            
            // 直接更新管理员密码
            int updated = jdbcTemplate.update(
                "UPDATE admins SET password = ? WHERE username = ?",
                encodedPassword, "admin"
            );
            
            result.put("success", true);
            result.put("message", "管理员密码已重置: " + updated + " 条记录更新");
            result.put("username", "admin");
            result.put("password", password);
            result.put("encodedPassword", encodedPassword);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "修复管理员密码时出错: " + e.getMessage());
            result.put("error", e.toString());
        }
        
        return result;
    }
    
    @GetMapping("/check-admin")
    public Map<String, Object> checkAdmin() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Map<String, Object> adminInfo = jdbcTemplate.queryForMap(
                "SELECT id, username, password FROM admins WHERE username = ?", 
                "admin"
            );
            
            result.put("success", true);
            result.put("message", "找到管理员账号");
            result.put("admin", adminInfo);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询管理员账号时出错: " + e.getMessage());
            result.put("error", e.toString());
        }
        
        return result;
    }
} 